/**
 * Get the agent details
 */
function initConvo(agentName) {
    $.ajax({
        url: "functions/ajax/getAgentDetails.php",
        context: self,
        type: "post",
        data: {name: agentName},
        success: function(data, textStatus, jqXHR) {
            var agent = jQuery.parseJSON(data);
            
            $("span#likes").html(arrayToStr(agent.likes))
            $("span#dislikes").html(arrayToStr(agent.dislikes))
        }
    });
}

function arrayToStr(arr) {
    var str = "";
    for (var i=0; i<arr.length; i++) {
        str += arr[i];
        if (i != arr.length-1) {
            str += ", ";
        }
    }
    return str;
}

function trustDialog() {
    var agentName = $("input#name").val();
    $.ajax({
        url: "functions/ajax/getQuestion.php",
        context: self,
        type: "post",
        data: {name: agentName},
        success: function(data, textStatus, jqXHR) {
            $.mobile.changePage('trust.php', {
                type: "post", 
                data: {
                    name: agentName,
                    question: data
                } 
            });
        }
    });
}

function askQuestion(questionName) {
    var agentName = $("input#name").val();
    $.ajax({
        url: "functions/ajax/askQuestion.php",
        context: self,
        type: "post",
        data: {name: agentName,
               questionType: questionName},
        success: function(data, textStatus, jqXHR) {
            var div;
            if (questionName == "personal") {
                initConvo(agentName);
                div = $("p#personalAnswer");
            } else if (questionName == "event") {
                div = $("p#eventAnswer");
            } else if (questionName == "theory") {
                div = $("p#theoryAnswer");
            }
            div.html(data);
            div.css("display", "block");
        }
    });
}

var initialized;
if (!initialized) {
    initialized = true;
    $('#conversation').live('pageinit',function(event){
        var agentName = $("input#name").val();
        initConvo(agentName);

        $("a#personalQuestion").click(function() {
            askQuestion("personal");
        });
        
        $("a#eventQuestion").click(function() {
            askQuestion("event");
        });
        
        $("a#theoryQuestion").click(function() {
            askQuestion("theory");
        });

        $("a#trustButton").click(function() {
            trustDialog();
        });

        $("p.answer").css("display", "none");
    });
}

